/*
 * @lc app=leetcode.cn id=637 lang=cpp
 *
 * [637] 二叉树的层平均值
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        if (root == nullptr)
            return {};
        
        std::vector<double> result;
        std::queue<TreeNode*> nodes;

        nodes.push(root);
        while (!nodes.empty()) {
            double sum = 0.0;
            int size = nodes.size();
            for (int i = 0; i < size; i++) {
                auto node = nodes.front();
                nodes.pop();

                if (node->left != nullptr) nodes.push(node->left);
                if (node->right != nullptr) nodes.push(node->right);

                sum += node->val;
            }

            result.push_back(sum / size);
        }

        return result;
    }
};
// @lc code=end

